package com.managertrade.util.strategy;

import com.managertrade.dto.vo.KlineWithIndicators;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Slf4j
public class TradeSignalUtil {
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 判断是否满足策略信号：
     * 条件1：1小时图 EMA7 上穿 EMA21；
     * 条件2：4小时图 MACD 金叉 + 柱子翻红 + MACD < 0。
     *
     * @param oneHourKlines   1小时K线集合（需按时间升序排列）
     * @param fourHourKlines  4小时K线集合（需按时间升序排列）
     * @return true 表示信号满足，可以出手；false 表示不满足
     */
    public static  Map<Boolean,String> isTradeSignal(List<KlineWithIndicators> oneHourKlines, List<KlineWithIndicators> fourHourKlines) {
        Map<Boolean,String> map =  new HashMap<>();
        // 最近两根K线
        KlineWithIndicators prev1h = oneHourKlines.get(oneHourKlines.size() - 2);
        KlineWithIndicators curr1h = oneHourKlines.get(oneHourKlines.size() - 1);

        KlineWithIndicators prev4h = fourHourKlines.get(fourHourKlines.size() - 2);
        KlineWithIndicators curr4h = fourHourKlines.get(fourHourKlines.size() - 1);

        // 条件1：1小时图 EMA7 上穿 EMA21
        boolean isEmaCross = prev1h.getEma7() != null && prev1h.getEma21() != null &&
                curr1h.getEma7() != null && curr1h.getEma21() != null &&
                prev1h.getEma7() <= prev1h.getEma21() &&
                curr1h.getEma7() > curr1h.getEma21();

        // 条件2：4小时图 MACD金叉 + 柱子翻红 + MACD < 0
        boolean isMacdCross = prev4h.getMacd() != null && prev4h.getSignal() != null &&
                curr4h.getMacd() != null && curr4h.getSignal() != null &&
                prev4h.getMacd() <= prev4h.getSignal() &&
                curr4h.getMacd() > curr4h.getSignal();

        boolean isHistogramRed = prev4h.getHistogram() != null && curr4h.getHistogram() != null &&
                prev4h.getHistogram() <= 0 && curr4h.getHistogram() > 0;

        boolean isMacdBelowZero = curr4h.getMacd() != null && curr4h.getMacd() < 0;

        boolean isMacdSignal = isMacdCross && isHistogramRed && isMacdBelowZero;


        boolean signal = isEmaCross && isMacdSignal;
        String msg = "";
        if (signal) {
            msg = msg +"=== 策略信号成立 ===";
            log.info("=== 策略信号成立 ===");
            log.info("【1小时K线】 时间: " + formatTimestamp(curr1h.getTimestamp())
                    + " 收盘价: " + curr1h.getClose()
                    + " EMA7: " + curr1h.getEma7()
                    + " EMA21: " + curr1h.getEma21());

            log.info("【4小时K线】 时间: " + formatTimestamp(curr4h.getTimestamp())
                    + " 收盘价: " + curr4h.getClose()
                    + " MACD: " + curr4h.getMacd()
                    + " Signal: " + curr4h.getSignal()
                    + " Histogram: " + curr4h.getHistogram());
            msg = msg +"【4小时K线】 时间: " + formatTimestamp(curr4h.getTimestamp())
                    + " 收盘价: " + curr4h.getClose()
                    + " MACD: " + curr4h.getMacd()
                    + " Signal: " + curr4h.getSignal()
                    + " Histogram: " + curr4h.getHistogram();
        }
        map.put(signal,msg);
        return map;
    }

    public static List<String> findAllMatchingSignals(List<KlineWithIndicators> oneHourList, List<KlineWithIndicators> fourHourList) {
        List<String> matches = new ArrayList<>();

        int minSize = Math.min(oneHourList.size(), fourHourList.size());
        for (int i = 1; i < minSize; i++) {
            KlineWithIndicators prev1h = oneHourList.get(i - 1);
            KlineWithIndicators curr1h = oneHourList.get(i);

            KlineWithIndicators prev4h = fourHourList.get(i - 1);
            KlineWithIndicators curr4h = fourHourList.get(i);

            boolean emaCross = prev1h.getEma7() <= prev1h.getEma21() && curr1h.getEma7() > curr1h.getEma21();
            boolean macdCross = prev4h.getMacd() <= prev4h.getSignal() && curr4h.getMacd() > curr4h.getSignal();
            boolean histFlip = prev4h.getHistogram() <= 0 && curr4h.getHistogram() > 0;
            boolean macdBelowZero = curr4h.getMacd() < 0;

            if (emaCross && macdCross && histFlip && macdBelowZero) {
                String entry = String.format(
                        "信号时间：%s\n价格：%.2f\nEMA7：%.4f  EMA21：%.4f\nMACD：%.4f  SIGNAL：%.4f  HISTOGRAM：%.4f",
                        formatTimestamp(curr1h.getTimestamp()),
                        curr1h.getClose(),
                        curr1h.getEma7(),
                        curr1h.getEma21(),
                        curr4h.getMacd(),
                        curr4h.getSignal(),
                        curr4h.getHistogram()
                );
                matches.add(entry);
            }
        }

        return matches;
    }

    public static String formatTimestamp(long ts) {
        return sdf.format(new Date(ts));
    }
}

